/*
 * @Author: crissu 13750782397@163.com
 * @Date: 2024-06-03 00:28:21
 * @LastEditors: crissu 13750782397@163.com
 * @LastEditTime: 2024-06-03 00:28:26
 * @FilePath: /try_concurrence/practice/case1.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package practice

import (
	"fmt"
	"sync"
)

// 练习题1：使用两个 goroutine 交替打印序列，一个 goroutine 打印数字，另外一个 goroutine 打印字母，最终效果如下：
func PrintABCByConcurrent1() {
	chanByte := make(chan struct{}, 1)
	chanNumber := make(chan struct{}, 1)
	one := 1
	a := 'a'
	chanNumber <- struct{}{}
	for {
		select {
		case <-chanByte:
			fmt.Println(string(a))
			a++
			chanNumber <- struct{}{}
		case <-chanNumber:
			fmt.Println(one)
			one++
			if one == 12 {
				return
			}
			chanByte <- struct{}{}
		}
	}
}

func PrintABCByConcurrent2() {
	numberList := []int{1, 2, 3, 4, 5, 6, 7}
	charList := []string{"A", "B", "C", "D", "E", "F", "G"}
	numberIdx := 0
	charIdx := 0
	ch := make(chan bool, 1)
	ch <- true
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		for {
			select {
			case v := <-ch:
				if v == true {
					if numberIdx < len(numberList) {
						fmt.Println(numberList[numberIdx])
					}
					numberIdx++
				}
				if numberIdx == len(numberList) {
					wg.Done()
				}
				ch <- false

				// default:
			}
		}
	}()
	go func() {
		for {
			select {
			case v := <-ch:
				if v == false {
					if charIdx < len(charList) {
						fmt.Println(charList[charIdx])
					}
					charIdx++
				}
				ch <- true
				if charIdx == len(charList) {
					wg.Done()
				}
				// default:
			}
		}
	}()
	wg.Wait()

}
